//
//  DetailTableViewController.swift
//  Cathy
//
//  Created by diandian on 14/12/9.
//  Copyright (c) 2014年 yangjie. All rights reserved.
//

import UIKit
import Alamofire

class DetailTableViewController: UITableViewController {
    
    var body:String?
    var detailArr:[V2EXDetail]?
    
    var request: Alamofire.Request? {
        
        didSet {
            oldValue?.cancel()
            self.refreshControl?.endRefreshing()
            self.body = nil;
        }
    }
    
    override func awakeFromNib() {
        
        let refreshControl = UIRefreshControl()
        self.refreshControl = refreshControl
        self.refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        self.refresh()
    }
    
    @IBAction func refresh() {
        
        println("refresh....")
        
        self.refreshControl?.beginRefreshing()
        
        // async download the latest data
        
        self.request = Alamofire.request(.GET, kV2EXLastestUrl)
        self.request?.responseJSON({ (_, _, JSON, _) -> Void in
            
            if let arr = JSON as? NSArray {
                
                for obj in arr {
                    
                    var dict:NSDictionary = obj as NSDictionary
                    
                    let title = dict["title"]  as String
                    let url = dict["url"] as String
                    let content = dict["content"] as String
                    
                    self.detailArr?.append(V2EXDetail(title: title, url: url, content: content))
                }
            }
            
            self.refreshControl?.endRefreshing()
            self.tableView.reloadData()
        })
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.detailArr?.count?
    }
}

























